const net = require('net')

const server = net.createServer()

const clients = []
server.on('connection', client => { // 服务端socket
  client.name = client.remoteAddress + ':' + client.remotePort
  client.write('Hi ' + client.name + ' !')
  clients.push(client)
  client.on('data', data => {
    console.log('emit data')
    console.log(`data is Buffer ? ${Buffer.isBuffer(data)}`)
    broadcast(data, client)
  })
  client.on('end', () => {
    console.log('emit end')
    clients.splice(clients.indexOf(client), 1)
  })
  client.on('error', e => {
    console.log(e)
  })
})

function broadcast (message, client) {
  let clean = []
  for (let i = 0; i < clients.length; i++) {
    if (client !== clients[i]) {
      if (clients[i].writable) {
        clients[i].write(client.name + ' says ' + message) // buffer + string = string
      } else {
        clean.push(clients[i])
        clients[i].destory()
      }
    }
  }
  for (let i = 0; i < clean.length; i++) {
    clients.splice(clients.indexOf(clean[i]), 1)
  }
}

server.listen(8888)
